<template>
  <div class="deviceReferenceConfig detailView">
    <Modal v-model="isView"
           :mask-closable="false"
           title="编辑设备指标"
           :footer-hide="true"
           width="70%">
      <el-form :model="item"
               label-position="right"
               label-width="100px"
               :rules="formRules"
               ref="form">
        <el-form-item label="检测项目：">
          <el-input v-model="item.name"
                    clearable
                    :disabled="true"
                    placeholder="请输入检测项目"
                    class="w-200"/>
        </el-form-item>
        <el-form-item label="检测指标："
                      prop="referenceId">
          <el-select v-model="selectReferenceId"
                     filterable
                     remote
                     clearable
                     placeholder="请输入检测指标"
                     :remote-method="remoteMethodTypeId1"
                     @change="addDeviceReference">
            <el-option v-for="item in referenceList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
              <span class="fl">{{item.name}}</span>
              <span class="fr"
                    style="color: #f78989">{{item.code}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-table :data="item.referenceDtoList"
                  border>
          <el-table-column prop="referenceName"
                           label="指标名称">
          </el-table-column>
          <el-table-column prop="code"
                           label="code">
          </el-table-column>
          <el-table-column prop="sortNum"
                           label="排序号"
                           width="250">
            <template slot-scope="{row}">
              <el-input clearable
                        class="w-200"
                        placeholder="请输入排序"
                        v-model="row.sortNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="content"
                           label="介绍"
                           width="250">
            <template slot-scope="{row}">
              <el-input type="textarea"
                        clearable
                        class="w-200"
                        placeholder="请输入介绍"
                        v-model="row.content"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="criterion"
                           label="判断标准"
                           align="center"
                           width="150">
            <template slot-scope="{row,$index}">
              <el-popover trigger="hover"
                          class="tip"
                          placement="right">
                <div v-for="(po, index) in row.criterionList"
                     :key="index">
                  <p>{{ po.result }}: {{ po.range }} ({{ po.typeValue }}) </p>
                </div>
                <div slot="reference"
                     class="name-wrapper">
                  <el-tag style="cursor: pointer"
                          @click="openConfig(row)">配置判断标准
                  </el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>


          <el-table-column prop="criterion"
                           label="特殊判断标准"
                           align="center"
                           width="150">
            <template slot-scope="{row,$index}">
              <el-tag style="cursor: pointer"
                      @click="specialJudgmentCriteria(row)">特殊判断标准
              </el-tag>

            </template>
          </el-table-column>

          <el-table-column label="操作"
                           width="180"
                           align="center">
            <template slot-scope="scope">
              <el-button type="success"
                         @click="handleSave(scope.row)">保 存
              </el-button>
              <el-button type="danger"
                         @click="handleDel(scope.row)">删 除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="operationView mt-20">
        <el-button type="primary"
                   @click="handleCancel">关 闭
        </el-button>
      </div>
    </Modal>
    <Modal v-model="isConfigView"
           :mask-closable="false"
           title="配置指标判断标准"
           :footer-hide="true"
           width="70%">
      <el-button type="success"
                 @click="addConfig(item)">新 增
      </el-button>
      <div v-for="(item, index) in criterionList"
           :key="index"
           class="mt-20">
        <el-card>
          <el-form :inline="true"
                   :model="item">
            <el-form-item label="结果">
              <el-input v-model="item.result"
                        placeholder="判断结果"
                        clearable
                        style="width: 100px"></el-input>
            </el-form-item>
            <el-form-item label="范围">
              <el-input v-model="item.leftValue"
                        placeholder="最小值"
                        style="width: 100px"></el-input>
              <el-select v-model="item.leftRelation"
                         placeholder="关系"
                         clearable
                         style="width: 120px">
                <el-option v-for="relation in relations_1"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
              <label>检测值</label>
              <el-select v-model="item.rightRelation"
                         placeholder="关系"
                         clearable
                         style="width: 120px">
                <el-option v-for="relation in relations_2"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
              <el-input v-model="item.rightValue"
                        placeholder="最大值"
                        clearable
                        style="width: 100px"></el-input>
            </el-form-item>
            <el-form-item label="条件">
              <el-select v-model="item.type"
                         placeholder="关系"
                         clearable
                         style="width: 120px"
                         @change="initValueList">
                <el-option v-for="relation in typeList"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
              <el-select v-model="item.typeValue"
                         placeholder="请选择关系"
                         clearable
                         style="width: 120px">
                <el-option v-for="relation in valueList"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
              <el-select v-model="item.status"
                         placeholder="请选择结论"
                         clearable
                         style="width: 120px">
                <el-option v-for="relation in stateDataSource"
                           :key="relation.status"
                           :label="relation.name"
                           :value="relation.status">
                </el-option>
              </el-select>
            </el-form-item>
            <div class="row-item">
              <el-form-item label="参考范围"
                            prop="referenceRange">
                <el-input v-model="item.referenceRange"
                          type="textarea"
                          style="width:100%;"
                          placeholder="请输入参考范围"></el-input>
              </el-form-item>
              <el-button type="warning"
                         @click="removeConfig(item)">移 除
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
      <div class="operationView mt-20">
        <el-button type="primary"
                   plain
                   @click="closeModal">取 消
        </el-button>
        <el-button type="primary"
                   @click="addItem">确 定
        </el-button>
      </div>
    </Modal>
    <dialog-conditon v-if="showDialog" :visible.sync="showDialog" :dataObj="dataObj"/>
  </div>
</template>

<script>
  import dialogConditionConfig from "../detectionReferenceMgt/dialogConditionConfig";

  export default {
    name: "deviceReferenceConfig",
    data() {
      return {
        showDialog: false,
        dataObj: {
          deviceId: '',
          detectionIndexId: '',
        },
        isView: false,
        isConfigView: false,
        editModel: {},
        item: {
          id: 0,
          deviceId: '',
          deviceName: '',
          referenceDtoList: []
        },
        selectReferenceId: null,
        loading: false,
        referenceList: [],
        criterionList: [],
        stateDataSource: [
          {
            status: 0,
            name: '异常'
          },
          {
            status: 1,
            name: '正常'
          }
        ],
        relations_1: [
          {
            value: '<',
            label: '大于'
          },
          {
            value: '<=',
            label: '大于等于'
          }
        ],
        relations_2: [
          {
            value: '<',
            label: '小于'
          },
          {
            value: '<=',
            label: '小于等于'
          },
          {
            value: '=',
            label: '等于'
          },
        ],
        typeList: [
          {
            value: 'sex',
            label: '性别'
          },
          {
            value: 'age',
            label: '年龄'
          },
          {
            value: 'bloodSugar',
            label: '血糖'
          },
          {
            value: 'adultMale',
            label: '成男'
          },
          {
            value: 'adultFemale',
            label: '成女'
          },
          {
            value: 'child',
            label: '儿童'
          },
          {
            value: 'common',
            label: '通用'
          }
        ],
        valueList: [],
        formRules: {},
      }
    },
    created() {
    },
    methods: {
      openView(row) {
        this.isView = true;
        this.$refs['form'].resetFields();
        this.item.id = 0;
        this.referenceList = [];
        this.selectReferenceId = null;
        if (row) {
          this.item = Object.assign({}, row);
          if (!this.item.referenceDtoList) {
            this.item.referenceDtoList = [];
          }
        }
        this.ajax({
          type: this.api.detectionReferenceList.type,
          url: this.api.detectionReferenceList.url,
          data: {
            pageSize: 50,
            pageStart: 0
          },
          success: (data) => {
            this.referenceList = data.object
          },
          error: (data) => {
            this.$Message.error(data.message);
          }
        })

      },
      handleCancel() {
        this.isView = false
        this.$refs['form'].resetFields();
      },
      handleDel(row) {
        this.$confirm('确认删除？')
          .then(_ => {
            this.ajax({
              type: this.api.deviceReferenceDel.type,
              url: this.api.deviceReferenceDel.url,
              data: {
                id: row.id
              },
              success: (data) => {
                for (let i = 0; i < this.item.referenceDtoList.length; i++) {
                  let temp = this.item.referenceDtoList[i];
                  if (temp.id === row.id) {
                    this.item.referenceDtoList.splice(i, 1);
                    break;
                  }
                }
                this.$message.success('删除成功!');
                this.$parent._getList();
              },
              error: (data) => {
                this.$Message.error(data.message);
              }
            })
          })
          .catch(_ => {
          });

      },
      openConfig: function (row) {
        this.editModel = row;
        this.criterionList = this.editModel.criterionList
        if (this.criterionList && this.criterionList.length > 0) {
          this.initValueList(this.criterionList[0].type);
        }
        this.isConfigView = true;
      },
      //特殊判断标准
      specialJudgmentCriteria(row) {
        this.showDialog = true
        this.dataObj.deviceId = row.deviceId
        this.dataObj.detectionIndexId = row.referenceId
      },
      closeModal() {
        this.isConfigView = false;
      },
      addItem() {
        this.isConfigView = false;
        this.editModel.criterion = JSON.stringify(this.criterionList);
      },
      addConfig() {
        let timestamp = new Date().getTime();
        this.criterionList.push({
          "id": timestamp,
          "result": "",
          "leftValue": null,
          "leftRelation": null,
          "rightRelation": null,
          "rightValue": null,
          "type": null,
          "typeValue": null,
          'status': ''
        })
      },
      removeConfig(item) {
        for (let i = 0; i < this.criterionList.length; i++) {
          if (this.criterionList[i].id) {
            if (item.id === this.criterionList[i].id) {
              this.criterionList.splice(i, 1);
              break;
            }
          }
        }
      },
      initValueList(obj) {
        if ("sex" == obj) {
          this.valueList = [{
            value: 1,
            label: '男'
          },
            {
              value: 0,
              label: '女'
            }];
        } else if ("age" == obj) {
          this.valueList = [];
        } else if ("bloodSugar" == obj) {
          this.valueList = [{
            value: 0,
            label: '凌晨'
          },
            {
              value: 2,
              label: '早餐后1H'
            },
            {
              value: 3,
              label: '早餐后2H'
            },
            {
              value: 4,
              label: '午餐前'
            },
            {
              value: 5,
              label: '午餐后1H'
            },
            {
              value: 6,
              label: '午餐后2H'
            },
            {
              value: 7,
              label: '晚餐前'
            },
            {
              value: 8,
              label: '晚餐后1H'
            },
            {
              value: 9,
              label: '晚餐后2H'
            },
            {
              value: 10,
              label: '睡前'
            },
            {
              value: 11,
              label: '空腹'
            },
            {
              value: 12,
              label: '餐后1小时'
            },
            {
              value: 13,
              label: '餐后2小时'
            },
            {
              value: 99,
              label: '随机血糖'
            }];
        }
      },
      handleSave(row) {
        this.post(this.api.deviceReferenceConfig.url, {
          id: row.id,
          deviceId: row.deviceId,
          referenceId: row.referenceId,
          content: row.content,
          sortNum: row.sortNum,
          criterion: row.criterion
        }).then(res => {
          if (res.data.code === '200') {
            this.$message.success("保存成功");
            this.$parent._getList()
          }
        });
      },
      // 每选一项检测指标,添加到下面的列表里面
      addDeviceReference(val) {
        if (this.item.referenceDtoList.some(item => item.referenceId === val)) {
          this.$message.error('不能重复添加检测指标!');
          this.selectReferenceId = '';
          return
        }
        this.ajax({
          type: this.api.deviceReferenceConfig.type,
          url: this.api.deviceReferenceConfig.url,
          data: {
            deviceId: this.item.id,
            referenceId: this.selectReferenceId
          },
          success: (data) => {
            this.item.referenceDtoList.push(data.object);
            this.selectReferenceId = '';
            this.$message.success('检测指标添加成功!');
            this.$parent._getList();
          },
          error: (data) => {
            this.$Message.error(data.message);
          }
        })
      },
      remoteMethodTypeId1(query) {
        if (query !== '') {
          this.loading = true;
          this.ajax({
            type: this.api.detectionReferenceList.type,
            url: this.api.detectionReferenceList.url,
            data: {
              pageSize: 20,
              pageStart: 0,
              name: query
            },
            success: (data) => {
              this.referenceList = data.object;
            },
            error: (data) => {
              this.$Message.error(data.message);
            }
          })
        } else {
          this.referenceList = [];
        }
        this.loading = false;
      }
    },
    components: {
      'dialog-conditon': dialogConditionConfig
    }
  }
</script>

<style lang="scss" scoped>
  .row-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    /deep/ .el-form-item {
      width: 100%;
    }

    /deep/ .el-form-item__content {
      width: 88%;
    }
  }
</style>
